import {Promise} from 'es6-promise';
import {Request, Response} from "express";

import PWSApp from "../../core/app";
import ApiBaseAction from "./act.base"
import {ErrCode} from "../../core/error.code";
import {RouteType} from "../../core/defines";
import {MongoColls} from "../../config/mongo";
import AppHomeModel from "../../models/mod.app.home";
import HomeModel from "../../models/mod.home";

declare function require(name: string): any;

export default class HomeAction extends ApiBaseAction {
    private _homeModel: AppHomeModel;
    private _homeMod: HomeModel;

    constructor(app: PWSApp){
        super(app);
        this._homeModel = new AppHomeModel(this.db.collection( MongoColls.PRODUCT ) );
        this._homeMod = new HomeModel( this.db.collection(MongoColls.HOME) );
    }

    name() { return `${this.app.name}HomeAPI`; }

    protected _setRoutes() {
        this._setRoot('/api');
        this._route(RouteType.GET,  '/', this._actGetHomeData);
        this._route(RouteType.GET,  '/home', this._actGetIndex);
    }

    private _actGetHomeData(req: Request, res: Response){
        this._homeModel.getHome().then((result) => {
            res.send({count: result.name});
        }).catch((err) => {
            this._errHandler(req, res, err);
        })
    }

    private _actGetIndex(req: Request, res: Response){
        Promise.resolve().then(()=> {
            return this._homeMod.getPublished();
        }).then((result: any) => {
            if( !result ) {
                return Promise.reject({ err_code: ErrCode.ResNotFound });
            }
            let homeData = result.online;
            homeData['err_code'] = ErrCode.Success;
            res.send(homeData);
        }).catch((err) => {
            this._errHandler(req, res, err);
        });
    }
}
